﻿using System;
using System.Collections.Generic;

using System.Diagnostics;



namespace DailyFx.AI
{
	public class RuledTask : ITask
	{
		/// <summary>
		///		the label of this task .
		/// </summary>
		private String _label;

		/// <summary>
		///		indicates if this is the final step .
		/// </summary>
		private bool _final = false;

		/// <summary>
		///		rules' conditions .
		/// </summary>
		private IList<ICondition> _conditions = new List<ICondition> ();


		/// <summary>
		///		c;tor
		/// </summary>
		public RuledTask (String label ) 
		{
			this._label = label;
		}

		public string Label 
		{
			get { return this._label; }
		}


		public RuledTask when ( ICondition condition )
		{
			this._conditions.Add ( condition);
			return this;
		}

		public RuledTask always ()
		{
			return this.when ( new Condition_AlwaysTrue() );
		}

		public RuledTask once ()
		{
			return this.when ( new Condition_AlwaysFalse() );
		}

		 public RuledTask or (ICondition condition)
		 { 
			 return this.when ( condition );
		 }

		public RuledTask and ( ICondition c1, ICondition c2 ) 
		{
			return this.when ( new SyntheticCondition(c1).and(c2) );
		}


		 public RuledTask final ( bool value ) 
		 {
			 this._final = value;
			 return this;
		}

		public bool final ()
		{
			return this._final;
		}

		 public bool IfAwaked ( IBlackboard blackboard )
		 {
			foreach (ICondition condition in this._conditions)
				if ( condition.Checks (this, blackboard) )
					return true;

			return false;
		 }

		public override bool Equals (Object obj )
		{
			if ( obj != null || !( obj is ITask) )
				return false;
			
			ITask t = (ITask)obj;
			return this.Label == t.Label ;
		}

		public override int GetHashCode () 
		{
			return this.Label.GetHashCode();
		}

		public override String ToString()
		{
			return "Rule based task \"" + this.Label + "\"";
		}

	}


}
